package com.lincoln.system.app;

import com.lincoln.bean.ApiCode;
import com.lincoln.bean.ApiCodeException;
import com.lincoln.bean.BaseSecurityApi;
import com.lincoln.repository.BaseRepositoryFactoryBean;
import com.lincoln.service.PermissionService;
import com.lincoln.service.RoleService;
import com.lincoln.service.TokenClientService;
import com.lincoln.service.UserService;
import com.lincoln.system.app.utils.RestTemplateUtils;
import com.lincoln.system.app.utils.WebParamUtils;
import org.json.JSONObject;
import org.json.XML;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

import static com.lincoln.bean.BaseApi.getRequest;

@SpringBootApplication
@EnableDiscoveryClient
@EntityScan({"com.lincoln.entity.*.*", "com.lincoln.entity"})
@EnableJpaRepositories(basePackages = {"com.lincoln.repository"},
        repositoryFactoryBeanClass = BaseRepositoryFactoryBean.class//指定自己的工厂类
)
@ComponentScan(basePackages = "com.lincoln.*")
@CrossOrigin
@RestController
public class SystemAppApplication {

    public static void main(String[] args) {
        SpringApplication.run(SystemAppApplication.class, args);
    }

    public static String api_modele_name = "auth-app";
    public static String base_url = "http://" + api_modele_name;

    @Bean
    @LoadBalanced
    RestTemplate restTemplate() {
        return new RestTemplate();
    }

    @Autowired
    RestTemplate restTemplate;
    @Autowired
    UserService userService;
    @Autowired
    TokenClientService tokenClientService;
    @Autowired
    RoleService roleService;
    @Autowired
    PermissionService permissionService;

    @PostMapping("/login")
    public ApiCode login() {
        Map<String, String> param = WebParamUtils.formatRequestMap(getRequest().getParameterMap());
        Map<String, String> params = new HashMap<>();
        for (String key : param.keySet()) {
            params.put(key, param.get(key));
        }
        params.put("grant_type", "password");
        params.put("clientId", "system-app");
        params.put("clientSecret", "systemapp");
        String xml = RestTemplateUtils.sendPost(restTemplate, "system-app", "systemapp", base_url + "/oauth/token", params, String.class);
        JSONObject xmlJSONObj = XML.toJSONObject(xml.replace("<xml>", "").replace("</xml>", ""));
        Map<String, Object> map = xmlJSONObj.toMap();
        ApiCode apiCode = ApiCode.findCode(ApiCode.SUCCESS);
        apiCode.setData(map);
        return apiCode;
    }

    @PostMapping("/refresh")
    public ApiCode refresh() throws ApiCodeException {
        Map<String, String> param = WebParamUtils.formatRequestMap(getRequest().getParameterMap());
        if (param.size() != 1 || param.get("refresh_token") == null) {
            throw new ApiCodeException(10001);
        }
        Map<String, String> params = new HashMap<>();
        params.put("grant_type", "refresh_token");
        params.put("clientId", "system-app");
        params.put("clientSecret", "systemapp");
        params.put("refresh_token", param.get("refresh_token"));
        String xml = RestTemplateUtils.sendPost(restTemplate, "system-app", "systemapp", base_url + "/oauth/token", params, String.class);
        JSONObject xmlJSONObj = XML.toJSONObject(xml.replace("<xml>", "").replace("</xml>", ""));
        Map<String, Object> map = xmlJSONObj.toMap();
        ApiCode apiCode = ApiCode.findCode(ApiCode.SUCCESS);
        apiCode.setData(map);
        return apiCode;
    }

    public boolean hasAdmin() throws ApiCodeException {
        if (userService.findAll().size() > 0) {
            if (BaseSecurityApi.getAuthorities().size() <= 0) {
                throw new ApiCodeException(10004);
            }
            boolean flag = false;
            for (GrantedAuthority grantedAuthority : BaseSecurityApi.getAuthorities()) {
                if ("role_admin".equals(grantedAuthority.getAuthority())) {
                    flag = true;
                }
            }
            if (flag == false) {
                throw new ApiCodeException(10004);
            }
            return true;
        } else {
            return true;
        }
    }
}
